package com.lxyk.controller;

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.http.HttpRequest;
import com.lxyk.pojo.Account;
import com.lxyk.service.AccountService;
import com.lxyk.utils.Sample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Random;


/**
 * @ClassName AccountController
 * @Description TODO
 * @Author FJQ
 * @Date 2022/10/21 14:49
 * @Version 1.0
 **/
@Controller
public class AccountController {

    @Autowired
    private AccountService service;


    /**
     * 密码登录
     * 处理浏览器用户登录的请求
     * 步骤：
     * 1 调用业务逻辑层对象AccountService的login方法判断用户名密码是否正确
     * 2 如果用户明密码正确，表示登录成功，跳转到送水公司后台管理系统主页
     * 3 否则，给出提示，不进行跳转
     * @param userName 表单采集的用户名
     * @param userPwd 表单采集的密码
     * @return 登录成功，跳转到送水公司后台管理系统主页，登录失败给出提示，重新回到登录页面
     */
    @RequestMapping("/login")
    public String loginFail(String userName, String userPwd, Model model, HttpSession session, HttpServletRequest request,HttpServletResponse response){
        boolean result = service.login(userName, userPwd);
        String remember = request.getParameter("remember");
        if ("1".equals(remember)){
            //勾选了，发送Cookie
            //1. 创建Cookie对象
            Cookie c_username = new Cookie("userName",userName);
            Cookie c_password = new Cookie("userPwd",userPwd);
            // 设置Cookie的存活时间
            c_username.setMaxAge( 60 * 60 * 24 * 7);
            c_password.setMaxAge( 60 * 60 * 24 * 7);
            //2. 发送
            response.addCookie(c_username);
            response.addCookie(c_password);
        }
        if (result){
            //登录成功 进入主页
            session.setAttribute("currentUser",userName);
            return "waterMainMenu";
        }else{
            //登录失败 给出提示信息  返回登录界面
            model.addAttribute("loginFail","用户名或密码错误");
            return "index";
        }
    }


    /**
     * 手机号登录
     * @param phoneCode
     * @param session
     * @param account
     * @return
     */
    @RequestMapping("/loginPhone")
    public String login(String phoneCode, HttpSession session,Account account){
        if(phoneCode==null || phoneCode.isEmpty() || phoneCode != ""){
            //如果不一致,跳转到登录页面,携带错误信息: 验证码错误
            session.setAttribute("loginFail","手机验证码错误");
            return "index";
        }
        //验证码通过, 判断用户
        Account login = service.login(account);
        if(login == null){
            //结果为空,说明没查到, 跳转到登录页面,携带错误信息: 用户名或密码错误
            session.setAttribute("loginFail","用户名或密码错误");
            return "index";
        }
        //不为空,登陆成功: 1.将用户信息存入session 2.跳转到信息列表展示页面
        session.setAttribute("currentUser",login.getUserName());
        return "waterMainMenu";
    }


    //发短信
    @RequestMapping("/sendMessage")
    @ResponseBody
    public String sendMessage(String phoneNum,HttpSession session) throws Exception {
        //1.生成验证码
        String code = getCheckCode();
        //2.向手机号发送验证码
        Sample.sendMessage(phoneNum,code);
        //3.向session中存一份
        session.setAttribute(phoneNum,code);
        return "OK";
    }

    /**
     * 产生4位数字
     */
    private String getCheckCode() {
        String base = "0123456789";
        int size = base.length();
        Random r = new Random();
        StringBuffer sb = new StringBuffer();
        for(int i=1;i<=4;i++){
            //产生0到size-1的随机值
            int index = r.nextInt(size);
            //在base字符串中获取下标为index的字符
            char c = base.charAt(index);
            //将c放入到StringBuffer中去
            sb.append(c);
        }
        return sb.toString();
    }


    @RequestMapping("/hello")
    public String hello(){
        return "waterMainMenu";
    }





    /**
     * 修改密码
     * @param userPwd
     * @param newPwd
     * @param model
     * @param session
     * @return
     */
    @RequestMapping("/pwdUp")
    public String pwdUp(String userPwd, String newPwd,Model model,HttpSession session){
        String UserName = (String) session.getAttribute("currentUser");
        boolean login = service.login(UserName, userPwd);
        if (login){
            Account account = new Account();
            account.setUserName(UserName);
            String encodePwd = DigestUtil.md5Hex(newPwd);
            account.setUserPwd(encodePwd);
            boolean b = service.pwdUser(account);
            if (b){
                return "index";
            }else {
                model.addAttribute("loginFail","修改失败！");
                model.addAttribute("currentUser",session.getAttribute("currentUser"));
                return "modifypwd";
            }
        }else {
            model.addAttribute("loginFail","修改失败！");
            model.addAttribute("currentUser",session.getAttribute("currentUser"));
            return "modifypwd";
        }
    }

    @RequestMapping("/pwd")
    public String pwd(Model model,HttpSession session){
        model.addAttribute("currentUser",session.getAttribute("currentUser"));
        return "modifypwd";
    }

}
